package manager.servlet;


import manager.bean.User;
import manager.dao.UserDao;
import manager.util.MD5;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/login",loadOnStartup = 1)
public class LoginServlet extends HttpServlet{
	UserDao dao= new UserDao();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		System.out.println(req.getServletContext().getRealPath("/"));
//接受参数
		String username = req.getParameter("username");
		String userpass = req.getParameter("userpass");
		// 获取session对象 （会话对象）
		// 从第一次访问服务器开始 tomcat服务器就会维护一个session对象
		// 1、自动注销 2、超时注销
		HttpSession session = req.getSession();

		//根据参数查询数据库
		String sql = "select * from t_user where username='"+username+"'";
		List<User> list = dao.getUser(sql);
		//根据查询结果  判断是否成功
		if (list.size()==1) {
			User d_user = list.get(0);
			if (MD5.compare_pass(userpass,d_user.getUserpass())) {
				int staff = d_user.getStaff_id();
				String sql1 = "select userstate from staff where id = "+staff;
				int res = dao.addUser(sql1);
				System.out.println(res+"------------------");
				if (res==0){
					System.out.println("00000000000000000000000000000");
					resp.getWriter().write("change_password");
				}else if (res==1){
					System.out.println("1111111111111111111111111");
					session.setAttribute("login_user",d_user);
					resp.getWriter().write("success");
					resp.getWriter().write(username);
				}else if (res==2){
					System.out.println("2222222222222222222");
					resp.getWriter().write("cant login");
				}
			}else {
				System.out.println("fffffffffffffffff");
				resp.getWriter().write("failure");
			}
		}
	}
}
